<?php
namespace common\models\sms;

use common\models\CacheKeys;
use common\models\Functions;
use common\services\SMS\SmsJiuqiu;
use \common\services\SMS\SmsParApi;
use yii\base\Exception;
use Yii;

class SMS
{
    const CONTENT_MAP = [
        CacheKeys::CACHE_CODE_TYPE_LOGIN => '本次登陆的验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_REGISTER_CODE => '此次用于注册的验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_FORGET_CODE => '此次用于找回密码的验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_RESET_PAY_PASS_CODE => '此次用于找回支付密码验证码为{code}，请在{time}分钟内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_MODIFY_PASSWORD_PHONE => '此次用于修改密码的验证码为{code}，请在{time}分钟内输入，切勿告知他人',
    ];

    public $appName = '';

    public function __construct() {
        $this->appName = Yii::$app->params['SMS_SIGN'];
    }

    /**
     * 发送短信并设置session
     * @param string $phone
     * @param string $type
     * @param int $time
     * @return array
     */
    public function sendCode($phone = '', $type = '', $time = 5) {
        try {
            if (empty(static::CONTENT_MAP[$type])) {
                throw new Exception('发送失败');
            }

//            //检查余量
//            $count = Count::getOneInfoById(1);
//
//            if ($count['sms_count'] < 1) {
//                throw new Exception('发送失败');
//            }

            $content = static::CONTENT_MAP[$type];
            $cacheKey = Functions::getVerifyKey($phone, $type);
            //校验时间间隔
            $cache = Yii::$app->cache;
            $lastData = json_decode($cache->get($cacheKey), true);
            if (!empty($lastData) && isset($lastData['send_time'])) {
                if ($lastData['send_time'] + 60 > time()) {
                    throw new Exception('时间间隔小于60秒', 2000);
                }
            }

            $code = rand(100000, 999999);

            $sendContent = str_replace('{code}',$code,$content);
            $sendContent = str_replace('{time}',$time,$sendContent);

            if($sendContent == '') {
                throw new Exception('发送内容不能为空');
            }
            $channel = strtolower(Yii::$app->request->headers->get('channel',''));
            $appName = $channel == "trade" ? "JDEX" : $this->appName;
            $sendContent = '【'.$appName.'】'.$sendContent;

            $this->sendSMS($phone, $sendContent, 1);
//            SMSLog::pushSms($phone, $sendContent);
            $data = [
                'code' => $code,
                'expire_time' => time() + $time * 60,
                'send_time' => time(),
                'to' => $phone
            ];
            $cache->set($cacheKey, json_encode($data), $time * 60);
            return Functions::formatJson(1000, '发送成功', $data);
        } catch (Exception $e) {
            return Functions::formatJson(2000, $e->getMessage());
        }
    }

    public function sendSMS($phone = '', $content = '', $type = 1) {
//        if (YII_DEBUG) {
//            $phone = "17662955088";
//        }

        if ($type == 1) {
            $smsJiuqiu = new SmsJiuqiu();
            $res = $smsJiuqiu->send($phone, $content);
            if($res['status'] != 0) {
                throw new Exception($res['message']);
            }
            
        } else {
            $sms = new SmsParApi();
            $res = $sms->send_sms($phone, $content);
            if(strstr($res,'error')) {
                throw new Exception('发送失败');
            }
        }
    }
    /**
     * 发送短信并设置session
     * @param string $phone
     * @param string $content
     *
     * @return array
     */
    public function sendNotice($phone = '', $content = '') {
        try {

            $sendContent = $content;

            if($sendContent == '') {
                throw new Exception('发送内容不能为空');
            }
            $sendContent = '【'.$this->appName.'】'.$sendContent;

            $this->sendSMS($phone, $sendContent, 1);

            return Functions::formatJson(1000, '发送成功');
        } catch (Exception $e) {
            return Functions::formatJson(2000, $e->getMessage());
        }
    }

}
